package com.self.campussecondhandmarket.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.campussecondhandmarket.entity.domain.Forum;
import com.self.campussecondhandmarket.entity.request.forum.AddReq;
import com.self.campussecondhandmarket.entity.response.forum.ListByType;
import com.self.campussecondhandmarket.mapper.ForumMapper;
import com.self.campussecondhandmarket.resp.Result;
import com.self.campussecondhandmarket.service.ForumService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 31465
 * @description 针对表【tb_forum(论坛表)】的数据库操作Service实现
 * @createDate 2024-04-14 13:31:37
 */
@Service
public class ForumServiceImpl extends ServiceImpl<ForumMapper, Forum>
		implements ForumService {
	
	@Override
	public void add(AddReq dto) {
		Forum forum = new Forum();
		forum.setContent(dto.getContent());
		forum.setType(dto.getType());
		List<String> strings = JSON.parseArray(dto.getImgs(), String.class);
		List<String> list = strings.stream().distinct().toList();
		String imgs = JSON.toJSONString(list);
		forum.setImg(imgs);
		this.baseMapper.insert(forum);
		
	}
	
	@Override
	public Result groupForum() {
		List<Forum> forums = this.baseMapper.selectList(null);
		Map<String, Long> collect = forums.stream().collect(Collectors.groupingBy(Forum::getType, Collectors.counting()));
		List<HashMap<String, Object>> list = collect.keySet().stream().map(o -> {
			HashMap<String, Object> vo = new HashMap<>();
			vo.put("type", o);
			vo.put("num", collect.get(o));
			return vo;
		}).toList();
		return Result.success(list);
	}
	
	@Override
	public Result getListByType(String type) {
		
		List<Forum> forums = this.baseMapper.selectList(Wrappers.<Forum>lambdaQuery().eq(Forum::getType, type));
		List<ListByType> list = forums.stream().map(o -> {
			ListByType listByType = new ListByType();
			BeanUtils.copyProperties(o, listByType);
			List<String> strings = JSON.parseArray(o.getImg(), String.class);
			listByType.setImgs(strings);
			return listByType;
		}).toList();
		
		return Result.success(list);
	}
}




